package com.example.oauth2.web;

import com.example.oauth2.util.APIResponse;
import com.example.oauth2.service.UserService;
import com.example.oauth2.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户controller
 */
@RestController
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    @Qualifier(value = "tokenService")
    private DefaultTokenServices tokenService;

    /**
     * 所有用户列表
     * @return
     */
    @GetMapping(value = "/user/list")
    public APIResponse getUserList() {
        return userService.getUserList();
    }

    /**
     * 创建一个用户
     * @param response
     * @param userVO
     * @return
     */
    @PostMapping(value = "/user/create")
    public APIResponse addUser(HttpServletResponse response, @RequestBody UserVO userVO) {
        APIResponse apiResponse = new APIResponse();
        apiResponse.setResponseCode(APIResponse.OK);
        response.setStatus(HttpServletResponse.SC_CREATED);
        return userService.addUser(userVO);
    }

    /**
     * 登出
     * @param request
     */
    @PostMapping(value = "/oauth/logout")
    public void logoutUser(HttpServletRequest request) {

        String authorization = request.getHeader("Authorization");
        if (authorization != null && authorization.contains("Bearer")) {
            String tokenId = authorization.substring("Bearer".length() + 1);
            tokenService.revokeToken(tokenId);
        }
    }

    public static void main(String[] args) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        System.out.println(passwordEncoder.encode("demoClientSecret"));
    }
}
